<?php

namespace common\models;


class CommonFunction
{
    /**
     * GET 请求
     * @param string $url
     */
    public static function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @return string content
     */
    public static function http_post($url, $param)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (is_string($param)) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /*
     * 随机获取字符串
     */
    public static function getRandChar($length, $is_str = true)
    {
        $str = null;
        $strPol = "0123456789";
        if($is_str)
            $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }


    /**
     * 活动样式IP
     * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param bool $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    public static function get_client_ip($type = 0,$adv=false) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown',$arr);
                if(false !== $pos) unset($arr[$pos]);
                $ip     =   trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    //id加密
    public static function id_encrypt($id){

        return intval($id);
    }

    public static function id_decrypt($id){

        return intval($id);
    }
    /**
     * @param string $data 加密数据
     * @param string $key 加密因子
     * @return string
     */
    public static function encrypt($data, $key = '')
    {
        !$key && $key = CommonVar::$encrypt;
        if(is_numeric($data)){
            $data = strval($data);
        }
        $key = md5($key);
        $x = 0;
        $len = strlen($data);
        $l = strlen($key);
        $char = '';
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) {
                $x = 0;
            }
            $char .= $key{$x};
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
        }
        return base64_encode($str);
    }

    //打印日志
    public static function log($info, $mkdir = '/data/www/ub/log/task'){
        if (!file_exists($mkdir))
            mkdir ($mkdir);
        $date = date('Y-m-d');
        if (!file_exists("$mkdir/$date"))
            mkdir ("$mkdir/$date");
        file_put_contents("$mkdir/$date/info.log", date('Y-m-d H:i:s')."[$info]\n", FILE_APPEND);
    }

    /**
     * @param string $data 加密数据
     * @param string $key 加密因子
     * @return string
     */
    public static function decrypt($data, $key = '')
    {
        !$key && $key = CommonVar::$encrypt;
        $key = md5($key);
        $x = 0;
        $data = base64_decode($data);
        $len = strlen($data);
        $l = strlen($key);
        $char = '';
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) {
                $x = 0;
            }
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            } else {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return $str;
    }

    /**
     * @return string
     * 生成唯一订单号
     */
    public static function buildOrder(){
        return date('Ymd'). substr(time(), -2) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    }

    /**
     * 公用密码加密方法
     * @param string $password 原始密码
     * @param string $encrypt加密盐
     * @param string $key公钥
     * @return string
     */
    public static function encryptPassword($password, $encrypt, $key = ''){
    !$key && $key = CommonVar::$encrypt;
    return md5($key . $password . $encrypt);
}

    public static function formatMoney($number, $fractional = true){
        $number = intval($number) / 100;
        if($fractional)
            return number_format($number, 2);
        return number_format($number);
    }

    /*
     * 处理银行卡显示
     */
    public static function dealBankCard($card){
        return substr(self::decrypt($card), -4);
    }
    /*
    * 金钱显示处理万元
    */
    public static function formatWan($number, $fractional = true){
        $number = intval($number) / 100;
        if($number > 10000){
            if($fractional)
                return number_format($number/10000, 2).'万';
            return number_format($number/10000).'万';
        }
        if($fractional)
            return number_format($number, 2);
        return number_format($number);
    }

    /*
     * 手机号显示
     *
     */
    public static function dealTel($phone){
        return substr($phone,  0, 2) . '********' . substr($phone,  -1, 1);
    }
    /**
     * 姓氏提取函数
     * @param string $full_name 全名
     * @return array 一维数组,元素一是姓,元素二为名
     * @author: 风柏杨<waitatlee@163.com>
     */
    public static function splitName($full_name, $flag = false){
        $hyphenated = array('欧阳','太史','端木','上官','司马','东方','独孤','南宫','万俟','闻人','夏侯','诸葛','尉迟','公羊','赫连','澹台','皇甫',
            '宗政','濮阳','公冶','太叔','申屠','公孙','慕容','仲孙','钟离','长孙','宇文','城池','司徒','鲜于','司空','汝嫣','闾丘','子车','亓官',
            '司寇','巫马','公西','颛孙','壤驷','公良','漆雕','乐正','宰父','谷梁','拓跋','夹谷','轩辕','令狐','段干','百里','呼延','东郭','南门',
            '羊舌','微生','公户','公玉','公仪','梁丘','公仲','公上','公门','公山','公坚','左丘','公伯','西门','公祖','第五','公乘','贯丘','公皙',
            '南荣','东里','东宫','仲长','子书','子桑','即墨','达奚','褚师');
        $vLength = mb_strlen($full_name, 'utf-8');
        $last_name = '';
        $first_name = '';//前为姓,后为名
        if($vLength > 2){
            $preTwoWords = mb_substr($full_name, 0, 2, 'utf-8');//取命名的前两个字,看是否在复姓库中
            if(in_array($preTwoWords, $hyphenated)){
                $last_name = $preTwoWords;
                $first_name = mb_substr($full_name, 2, 10, 'utf-8');
            }else{
                $last_name = mb_substr($full_name, 0, 1, 'utf-8');
                $first_name = mb_substr($full_name, 1, 10, 'utf-8');
            }
        }elseif($vLength == 2){//全名只有两个字时,以前一个为姓,后一下为名
            $last_name = mb_substr($full_name ,0, 1, 'utf-8');
            $first_name = mb_substr($full_name, 1, 10, 'utf-8');
        }else{
            $last_name = $full_name;
        }
        if($flag){
            return array($last_name, $first_name);
        }else{
            return $last_name;
        }
    }

    /**
     * 真实姓名过滤函数
     * 根据 身份证信息 或者 性别 将用户姓名转换成 姓+先生/女士
     * @param string $realName 真实姓名
     * @param string|int $flag 可以是身份证信息(加密或者非加密都可，或者直接是性别值：1=>男；2=>女)
     * @return string
     */
    public static function filterRealName($realName, $flag){
        //提取姓氏
        $last_name = CommonFunction::splitName($realName);
        //判断性别
        if($flag === 1 || $flag == 2){
            $sex = $flag;
        }else{
            $sex = CommonFunction::getUserInfoByIdentity($flag);
        }
        switch($sex){
            case 1:
                $last_name .= "先生";
                break;
            case 2:
                $last_name .= "女士";
                break;
            default:
                $last_name .= "某某";
        }
        return $last_name;
    }

    /*
     * 检查密码强度
     * @param string $str 原始密码;
     */
    public static function checkPasswordStrength($str){
        $result = preg_match('/.*[~!@#$%^&*()_+].*/', $str) + preg_match('/.*\d.*/', $str) + preg_match('/.*[a-z].*/', $str) + preg_match('/.*[A-Z].*/', $str);

        if($result > 1)
            return $result - 1;
        else
            return $result;
    }
    /**
     * 处理身份证
     * @param $id_no
     * @return array
     */
    public static function id_no_deal($id_no){
        $id_no = CommonFunction::decrypt($id_no);
        $id_type = strlen($id_no);
        $id_type == 18 ? $age_param = 0: $age_param = 2;
        $birthday_year = intval(substr($id_no, 6 , 4 - $age_param));
        $id_type == 15 && $birthday_year = $birthday_year + 1900;
        $birthday_month = intval(substr($id_no, 10 - $age_param, 4));
        $year_cur = intval(date('Y'));
        $month_cur = intval(date('md'));
        $age = $year_cur - $birthday_year;
        $month_cur < $birthday_month && $age--;
        $id_type == 18 ? $sex_param = -2: $sex_param = -1;
        $sex = (intval(substr($id_no, $sex_param, 1)) + 2) % 2;
        $sex == 0 && $sex = 2;
        return ['sex'=>$sex, 'age'=>$age];
    }

    /**
     * 短信发送方法
     * @param $mobile 发送的手机号
     * @param $content 发送内容
     * @return bool
     */
    static public function SMSSend($mobile, $content){
        $apiKey = '190b3ee64117644825e47c82d6cfea82';
        $url = 'https://sms.yunpian.com/v2/sms/single_send.json';
        $data['apikey'] = $apiKey;
        $data['mobile'] = $mobile;
        $data['text'] = $content;
        $return = json_decode(CommonFunction::http_post($url,$data),true);
        if($return['code'] == 0){
            return true;
        }else{
            return false;
        }
    }
}